#include "CCSlot.h"
#include "CCBone.h"
#include "CCSkin.h"
#include "CCSkeletalSprite.h"
#include "CCAttachment.h"

NS_CC_BEGIN

CCSlot::CCSlot() :
m_flags(0) {
	m_originalState.color = ccc4(255,255,255,255);
	m_originalState.activeAttachmentName = NULL;
    m_originalState.preAttachmenName=NULL;
	m_originalState.sprite = NULL;
    m_originalState.additive=false;
}

CCSlot::~CCSlot() {
    if(m_originalState.activeAttachmentName) {
		free((char*)m_originalState.activeAttachmentName);
	}
}

CCSlot* CCSlot::create() {
	CCSlot* s = new CCSlot();
	return (CCSlot*)s->autorelease();
}

void CCSlot::clearState(CCSkeletalSprite* owner) {
	StateMap::iterator iter = m_stateMap.find(owner);
	if(iter != m_stateMap.end()) {
		m_stateMap.erase(iter);
	}
}

CCSlot::State& CCSlot::getState(CCSkeletalSprite* owner) {
	StateMap::iterator iter = m_stateMap.find(owner);
	if(iter != m_stateMap.end()) {
		return iter->second;
	} else {
        m_stateMap.insert(make_pair(owner, m_originalState));
		iter = m_stateMap.find(owner);
		return iter->second;
	}
}

CCAttachment* CCSlot::getActiveAttachment(CCSkeletalSprite* owner) {
	State& state = getState(owner);
    
	// if attachment name is NULL, return
	if(!state.activeAttachmentName) {
		return NULL;
    }
    
    CCSkin* skin=owner->getSkin();
    
    if (!skin) {
        CCLog("spine error | the skin:%s is not find!",owner->getSkin()->getName());
        return NULL;
    }
    
    CCAttachment* rt=skin->getAttachment(this, state.activeAttachmentName);
    if (!rt) {
        skin=owner->getSkeleton()->getSkin("default");
        rt=skin->getAttachment(this, state.activeAttachmentName);
    }
    return rt;
}

NS_CC_END